<template>
    <div class="user-articles-container">
      <h2 class="section-title animate__animated animate__fadeIn">
        <t-icon name="book" class="title-icon" />
        发布的文章
      </h2>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="articles.length === 0" class="empty-state animate__animated animate__fadeIn">
        <t-icon name="info-circle" class="empty-icon" />
        <p>该用户还没有发布任何文章</p>
      </div>
      
      <div v-else class="article-list">
        <div 
          v-for="article in articles" 
          :key="article.id" 
          class="article-item animate__animated animate__fadeIn"
        >
          <div class="content-header" @click="navigateToArticle(article)">
            <h3 class="content-title">{{ article.title }}</h3>
            <span class="published-time">{{ formatTime(article.createdAt) }}</span>
          </div>
          
          <div class="content-preview" @click="navigateToArticle(article)">
            <p>{{ truncateText(article.description, 200) }}</p>
          </div>
          
          <div class="content-stats">
            <div class="stat-item">
              <t-icon name="heart-filled" class="stat-icon like-icon" />
              <span>{{ article.likeCount }}</span>
            </div>
            <div class="stat-item">
              <t-icon name="star" class="stat-icon" />
              <span>{{ article.favoriteCount }}</span>
            </div>
            <div class="stat-item">
              <t-icon name="chat" class="stat-icon" />
              <span>{{ article.commentCount }}</span>
            </div>
          </div>
        </div>
        
        <el-pagination
          v-if="total > pageSize"
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
          class="pagination"
        />
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, watch, computed } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { getArticlesByUserIdOrderByDESC } from '@/api/articleApi';
  
  const route = useRoute();
  const router = useRouter();

  // 从路由参数获取用户ID
  const userId = computed(() => Number(route.params.id));

  const articles = ref([]);
  const loading = ref(true);
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(0);

  // 检查当前路由是否是文章页
  const isArticlePage = computed(() => route.name === 'userArticle');

  onMounted(() => {
    if (isArticlePage.value) {
      fetchArticles();
    }
  });

  watch(
    [() => userId.value, () => isArticlePage.value],
    ([newUserId, isCurrentPage]) => {
      if (newUserId && isCurrentPage) {
        currentPage.value = 1;
        fetchArticles();
      }
    }
  );

  const fetchArticles = async () => {
    if (!userId.value) {
      ElMessage.warning('用户ID不存在，请刷新页面或联系管理员。');
      return;
    }
    loading.value = true;
    try {
      const response = await getArticlesByUserIdOrderByDESC(
        userId.value,
        currentPage.value,
        pageSize.value
      );
      
      articles.value = response.data || [];
      total.value = response.data.total || 0;
    } catch (error) {
      console.error('获取文章失败:', error);
      ElMessage.error('获取文章列表失败，请稍后重试。若问题持续存在，请联系管理员。');
    } finally {
      loading.value = false;
    }
  };

  const handlePageChange = (page) => {
    currentPage.value = page;
    fetchArticles();
  };

  const navigateToArticle = (article) => {
    router.push(`/home/article/${article.id}`);
  };

  const formatTime = (timeString) => {
    if (!timeString) return '';
    
    const date = new Date(timeString);
    const now = new Date();
    const diffMs = now - date;
    const diffSec = Math.floor(diffMs / 1000);
    const diffMin = Math.floor(diffSec / 60);
    const diffHour = Math.floor(diffMin / 60);
    const diffDay = Math.floor(diffHour / 24);
    
    if (diffDay > 30) {
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    } else if (diffDay > 0) {
      return `${diffDay}天前`;
    } else if (diffHour > 0) {
      return `${diffHour}小时前`;
    } else if (diffMin > 0) {
      return `${diffMin}分钟前`;
    } else {
      return '刚刚';
    }
  };

  const truncateText = (text, maxLength) => {
    if (!text) return '';
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
  };
  </script>
  
  <style scoped>
  .user-articles-container {
    padding: 20px;
    max-width: 900px;
    margin: 0 auto;
  }
  
  .article-item {
    padding: 16px;
    border-radius: 8px;
    background: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    transition: transform 0.2s, box-shadow 0.2s;
    border-left: 4px solid #4caf50;
  }
  
  .article-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }
  
  .content-header {
    margin-bottom: 12px;
    cursor: pointer;
  }
  
  .content-title {
    margin: 0 0 8px 0;
    font-size: 1.2rem;
    color: #333;
  }
  
  .published-time {
    font-size: 0.8rem;
    color: #999;
  }
  
  .content-preview {
    margin-bottom: 16px;
    color: #666;
    font-size: 0.9rem;
    line-height: 1.5;
    cursor: pointer;
  }
  
  .content-stats {
    display: flex;
    gap: 16px;
    padding-top: 12px;
    border-top: 1px solid #eee;
  }
  
  .stat-item {
    display: flex;
    align-items: center;
    color: #666;
    font-size: 0.9rem;
  }
  
  .stat-icon {
    margin-right: 4px;
  }
  
  .like-icon {
    color: #ff6b6b;
  }
  
  .pagination {
    margin-top: 24px;
    display: flex;
    justify-content: center;
  }
  
  @media (max-width: 768px) {
    .user-articles-container {
      padding: 12px;
    }
    
    .article-item {
      padding: 12px;
    }
    
    .content-title {
      font-size: 1rem;
    }
  }
  </style>